package com.cn.hotel.util;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class Upload {
    private static final String url = "/uploadImg/";
    private static final String basePath="D:\\chengduwanxi\\businesshotel-front-07\\out\\artifacts\\businesshotel_front_07_war_exploded";

    public static void imgUpload(HttpServletRequest req) {
        FileItemFactory factory = new DiskFileItemFactory();

        // 文件上传处理器
        ServletFileUpload upload  = new ServletFileUpload(factory);

        // 解析请求信息
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 对请求信息进行判断,Iterator和list的优缺点
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // 信息为普通的格式
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                String value = item.getString();
                try {
                    req.setAttribute(fieldName, new String(value.getBytes("ISO-8859-1"), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            // 信息为文件格式
            else {
//                E:\wanxi\aa.jpg
                String fileName = item.getName();//获得上传图片的名称
                int index = fileName.lastIndexOf("\\");
                fileName = new Date().getTime() + "-" + fileName.substring(index + 1);
                String fieldName = item.getFieldName();
                req.setAttribute(fieldName, url + fileName);
                File file = new File(basePath, url + fileName);
                try {
                    item.write(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
